package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private RabbitService rabbitService;

	/**
	 * 获取用户当前播放进度
	 * @param trackId
	 * @param userId
	 * @return
	 */
	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		//从mongodb中获取数据
		Query query =Query.query(Criteria.where("trackId").is(trackId).and("userId").is(userId));
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		if (null == userListenProcess){
			return new BigDecimal("0.00");
		}
		return userListenProcess.getBreakSecond();
	}

	/**
	 * 更新用户播放进度
	 * @param userListenProcessVo
	 * @param userId
	 */
	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
		//从mongodb中获取数据
		Query query = Query.query(Criteria.where("trackId").is(userListenProcessVo.getTrackId()));
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		if (null == userListenProcess){
			//第一次播放 存储数据
			//创建对象
			userListenProcess = new UserListenProcess();
			userListenProcess.setUserId(userId);
			userListenProcess.setUpdateTime(new Date());
			userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			userListenProcess.setIsShow(1);
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setTrackId(userListenProcessVo.getTrackId());
		}else {
			//不是第一次播放
			userListenProcess.setUpdateTime(new Date());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
		}
		//保存数据
		mongoTemplate.save(userListenProcess,collectionName);
		//播放完成后 播放量+1 防止用户刷单 用户一天内有效 第一次播放量+1 第二次播放量不+1
		//存储到缓存中 setnx key不存在时生效
		String key = userId+":"+userListenProcessVo.getTrackId();
		Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, 1, 1, TimeUnit.DAYS);
		if (aBoolean){
			//更新播放量
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-",""));
			trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
			trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setCount(1);
			//发送消息
			rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
		}
	}

	/**
	 * 获取最近一次播放声音
	 * @param userId
	 * @return
	 */
	@Override
	public Map<String, Object> getLatelyTrack(Long userId) {
		//创建对象
		Map<String, Object> map = new HashMap<>();
		//查询数据 并进行降序 获取第一条数据
		Query query = new Query();
		query.with(Sort.by(Sort.Direction.DESC,"updateTime")).limit(1);
		  //获取最近播放的声音
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		List<UserListenProcess> userListenProcesses = mongoTemplate.find(query, UserListenProcess.class, collectionName);
		//获取数据
		if (userListenProcesses.size()>0){
			map.put("albumId",userListenProcesses.get(0).getAlbumId());
			map.put("trackId",userListenProcesses.get(0).getTrackId());
		}
		return map;
	}
}
